package user

import (
	"context"
	"fmt"
	"goProject/api/auth"
	"goProject/cfg"
	"goProject/db"
	"goProject/table"
	"net/http"
	"time"

	"gitee.com/ruige_fun/util/std"
	"github.com/kataras/iris/v12"
)

type pUpdatePassword struct {
	User   string `json:"user" validate:"required,min=6,max=20"`
	Pwd    string `json:"pwd" validate:"required,min=6,max=255"`
	NewPwd string `json:"new_pwd" validate:"required,min=6,max=255"`
}

func updatePassword(c iris.Context) {
	var p pUpdatePassword
	err := c.ReadBody(&p)
	if err != nil {
		c.JSON(std.NewResp(http.StatusBadRequest, "参数校验失败", nil, nil))
		return
	}
	if v := db.RedisToken.Get(context.Background(), fmt.Sprint(cfg.Config.Main.ProjectName+"_login_blacklist_", p.User, "_", c.RemoteAddr())).Val(); v != "" {
		c.JSON(std.NewResp(http.StatusBadRequest, "距离上次输错密码时间过短，请稍后重试。", nil, nil))
		return
	}
	var u table.User
	err = db.MySQL.Where("`username` = ?", p.User).First(&u).Error
	if err != nil {
		db.RedisToken.Set(context.Background(), fmt.Sprint(cfg.Config.Main.ProjectName+"_login_blacklist_", p.User, "_", c.RemoteAddr()), time.Now().Unix()+10, time.Second*10) //黑名单
		c.JSON(std.NewResp(http.StatusBadRequest, "用户名或密码错误，请 10 秒后重试。", nil, nil))
		return
	}
	if false == auth.VerifyPassword(u, p.Pwd) {
		db.RedisToken.Set(context.Background(), fmt.Sprint(cfg.Config.Main.ProjectName+"_login_blacklist_", p.User, "_", c.RemoteAddr()), time.Now().Unix()+10, time.Second*10) //黑名单
		c.JSON(std.NewResp(http.StatusBadRequest, "用户名或密码错误，请 10 秒后重试。", nil, nil))
		return
	}
	if u.Lock == 2 {
		c.JSON(std.NewResp(http.StatusBadRequest, "您的账号已被锁定，请联系管理员解决。", nil, nil))
		return
	}
	password := auth.CypherPassword(u.Username, p.NewPwd)
	db.MySQL.Select("Password").Where("`id` = ?", u.ID).Updates(&table.User{
		Password: password,
	})
	_ = auth.Token.Del(fmt.Sprint(c.GetID()))
	c.JSON(std.NewResp(http.StatusOK, "", nil, nil))
}
